<template>
	<view class="customer-service-stats">
		<!-- 过滤器 -->
		<view class="filter-bar">
			<view class="date-filter">
				<view class="filter-label">统计日期：</view>
				<view class="date-picker">
					<picker mode="date" :value="date" @change="onDateChange">
						<view class="picker-value">{{ date }}</view>
					</picker>
				</view>
			</view>
			
			<view class="refresh-btn" @click="loadStats">
				<text class="refresh-icon">🔄</text>
				<text>刷新</text>
			</view>
		</view>
		
		<!-- 统计总览卡片 -->
		<view class="stats-overview">
			<view class="stat-card">
				<view class="stat-title">今日总会话</view>
				<view class="stat-value">{{ summaryStats.totalSessions }}</view>
			</view>
			
			<view class="stat-card">
				<view class="stat-title">平均响应时间</view>
				<view class="stat-value">{{ formatSeconds(summaryStats.avgResponseTime) }}</view>
			</view>
			
			<view class="stat-card">
				<view class="stat-title">平均会话时长</view>
				<view class="stat-value">{{ formatSeconds(summaryStats.avgSessionDuration) }}</view>
			</view>
			
			<view class="stat-card">
				<view class="stat-title">平均满意度</view>
				<view class="stat-value">{{ summaryStats.satisfactionAvgScore.toFixed(1) }}</view>
			</view>
		</view>
		
		<!-- 排行榜 -->
		<view class="section-card">
			<view class="section-title">客服排行榜</view>
			
			<view class="ranking-list">
				<view class="ranking-header">
					<view class="ranking-th rank">排名</view>
					<view class="ranking-th name">客服工号</view>
					<view class="ranking-th sessions">会话数</view>
					<view class="ranking-th response">响应时间</view>
					<view class="ranking-th duration">会话时长</view>
					<view class="ranking-th satisfaction">满意度</view>
				</view>
				
				<view 
					class="ranking-item" 
					v-for="(service, index) in rankingList" 
					:key="index"
					:class="{ 'top-rank': index < 3 }"
				>
					<view class="ranking-td rank">
						<view class="rank-badge" :class="`rank-${index + 1}`" v-if="index < 3">{{ index + 1 }}</view>
						<view v-else>{{ index + 1 }}</view>
					</view>
					<view class="ranking-td name">{{ service.serviceCode || '未知' }}</view>
					<view class="ranking-td sessions">{{ service.totalSessions }}</view>
					<view class="ranking-td response">{{ formatSeconds(service.avgResponseTime) }}</view>
					<view class="ranking-td duration">{{ formatSeconds(service.avgSessionDuration) }}</view>
					<view class="ranking-td satisfaction">
						<view class="satisfaction-stars">
							<text v-for="i in 5" :key="i" class="star" :class="{ active: i <= Math.round(service.satisfactionAvgScore) }">★</text>
						</view>
						<text class="satisfaction-score">{{ service.satisfactionAvgScore.toFixed(1) }}</text>
					</view>
				</view>
				
				<view class="empty-data" v-if="rankingList.length === 0">
					<text>暂无数据</text>
				</view>
			</view>
		</view>
		
		<!-- 详细统计 -->
		<view class="section-card">
			<view class="section-title">详细统计</view>
			
			<view class="stats-table">
				<view class="table-header">
					<view class="th">客服工号</view>
					<view class="th">会话数</view>
					<view class="th">转入数</view>
					<view class="th">转出数</view>
					<view class="th">响应时间</view>
					<view class="th">会话时长</view>
					<view class="th">满意度</view>
					<view class="th">操作</view>
				</view>
				
				<view class="table-body">
					<view class="tr" v-for="(stat, index) in statsList" :key="index">
						<view class="td">{{ stat.serviceCode || '未知' }}</view>
						<view class="td">{{ stat.totalSessions }}</view>
						<view class="td">{{ stat.transferInCount }}</view>
						<view class="td">{{ stat.transferOutCount }}</view>
						<view class="td">{{ formatSeconds(stat.avgResponseTime) }}</view>
						<view class="td">{{ formatSeconds(stat.avgSessionDuration) }}</view>
						<view class="td">{{ stat.satisfactionAvgScore.toFixed(1) }}</view>
						<view class="td">
							<button class="btn btn-small btn-primary" @click="viewDetails(stat)">查看详情</button>
						</view>
					</view>
					
					<view class="tr empty-row" v-if="statsList.length === 0">
						<view class="td" colspan="8">暂无数据</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 数据详情模态框 -->
		<view class="modal" v-if="showDetailsModal">
			<view class="modal-mask" @click="showDetailsModal = false"></view>
			<view class="modal-content">
				<view class="modal-header">
					<view class="modal-title">客服 {{ detailData.serviceCode }} 的工作统计</view>
					<view class="modal-close" @click="showDetailsModal = false">×</view>
				</view>
				
				<view class="modal-body">
					<view class="detail-section">
						<view class="detail-title">基本信息</view>
						<view class="detail-item">
							<view class="detail-label">统计日期</view>
							<view class="detail-value">{{ date }}</view>
						</view>
						<view class="detail-item">
							<view class="detail-label">客服工号</view>
							<view class="detail-value">{{ detailData.serviceCode }}</view>
						</view>
					</view>
					
					<view class="detail-section">
						<view class="detail-title">会话统计</view>
						<view class="detail-item">
							<view class="detail-label">总会话数</view>
							<view class="detail-value">{{ detailData.totalSessions }}</view>
						</view>
						<view class="detail-item">
							<view class="detail-label">转入会话数</view>
							<view class="detail-value">{{ detailData.transferInCount }}</view>
						</view>
						<view class="detail-item">
							<view class="detail-label">转出会话数</view>
							<view class="detail-value">{{ detailData.transferOutCount }}</view>
						</view>
					</view>
					
					<view class="detail-section">
						<view class="detail-title">会话质量</view>
						<view class="detail-item">
							<view class="detail-label">平均响应时间</view>
							<view class="detail-value">{{ formatSeconds(detailData.avgResponseTime) }}</view>
						</view>
						<view class="detail-item">
							<view class="detail-label">平均会话时长</view>
							<view class="detail-value">{{ formatSeconds(detailData.avgSessionDuration) }}</view>
						</view>
						<view class="detail-item">
							<view class="detail-label">平均满意度评分</view>
							<view class="detail-value">
								<view class="satisfaction-stars">
									<text v-for="i in 5" :key="i" class="star" :class="{ active: i <= Math.round(detailData.satisfactionAvgScore || 0) }">★</text>
								</view>
								{{ (detailData.satisfactionAvgScore || 0).toFixed(1) }}
							</view>
						</view>
					</view>
					
					<view class="detail-section">
						<view class="detail-title">操作</view>
						<button class="btn btn-primary" @click="recalculateStats(detailData.serviceId)">重新计算统计</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '../api/index.js';
	import { formatTimeArray, getRelativeTime } from '@/utils/dateUtils.js';
	
	export default {
		name: 'CustomerServiceStats',
		data() {
			return {
				date: this.formatDate(new Date()),
				statsList: [],
				rankingList: [],
				summaryStats: {
					totalSessions: 0,
					avgResponseTime: 0,
					avgSessionDuration: 0,
					satisfactionAvgScore: 0
				},
				showDetailsModal: false,
				detailData: {},
				serviceMap: {} // 用于存储客服ID和工号的映射
			}
		},
		mounted() {
			this.loadServiceList();
			this.loadStats();
		},
		methods: {
			onDateChange(e) {
				this.date = e.detail.value;
				this.loadStats();
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			async loadServiceList() {
				try {
					const res = await api.customerService.getAllServices();
					if (res.code === 200 && res.data) {
						const services = res.data || [];
						this.serviceMap = {};
						services.forEach(service => {
							this.serviceMap[service.id] = service.serviceCode;
						});
						return true;
					} else {
						uni.showToast({
							title: res.message || '加载客服列表失败',
							icon: 'none'
						});
						return false;
					}
				} catch (error) {
					console.error('加载客服列表失败:', error);
					uni.showToast({
						title: '加载客服列表失败',
						icon: 'none'
					});
					return false;
				}
			},
			async loadStats() {
				try {
					// 先确保客服列表加载成功
					const serviceListLoaded = await this.loadServiceList();
					if (!serviceListLoaded) {
						return;
					}

					uni.showLoading({
						title: '加载中...',
						mask: true
					});

					const res = await api.customerService.getServiceDailyStats({
						date: this.date
					});

					if (res.code === 200) {
						// 处理统计数据
						let statsData = [];
						if (Array.isArray(res.data)) {
							statsData = res.data;
						} else if (res.data && typeof res.data === 'object') {
							// 如果是对象格式，转换为数组
							statsData = Object.values(res.data);
						} else {
							statsData = [];
						}

						// 添加客服工号
						this.statsList = statsData.map(stat => ({
							...stat,
							serviceCode: this.serviceMap[stat.serviceId] || '未知'
						}));
						
						// 计算汇总数据
						this.calculateSummaryStats(statsData);

						// 获取排名数据
						try {
							const rankingRes = await api.customerService.getServiceRanking({ 
								date: this.date 
							});
							
							if (rankingRes.code === 200) {
								let rankingData = [];
								if (Array.isArray(rankingRes.data)) {
									rankingData = rankingRes.data;
								} else if (rankingRes.data && typeof rankingRes.data === 'object') {
									rankingData = Object.values(rankingRes.data);
								}

								this.rankingList = rankingData.map(stat => ({
									...stat,
									serviceCode: this.serviceMap[stat.serviceId] || '未知'
								}));
							} else {
								console.error('获取排名数据失败:', rankingRes.message);
								this.rankingList = [];
							}
						} catch (rankingError) {
							console.error('获取排名数据失败:', rankingError);
							this.rankingList = [];
						}
					} else {
						console.error('加载统计数据失败:', res.message);
						uni.showToast({
							title: res.message || '加载统计数据失败',
							icon: 'none'
						});
						this.statsList = [];
						this.rankingList = [];
						this.calculateSummaryStats([]);
					}
				} catch (error) {
					console.error('加载统计数据失败:', error);
					uni.showToast({
						title: '加载统计数据失败',
						icon: 'none'
					});
					this.statsList = [];
					this.rankingList = [];
					this.calculateSummaryStats([]);
				} finally {
					uni.hideLoading();
				}
			},
			calculateSummaryStats(stats) {
				if (!stats || stats.length === 0) {
					this.summaryStats = {
						totalSessions: 0,
						avgResponseTime: 0,
						avgSessionDuration: 0,
						satisfactionAvgScore: 0
					};
					return;
				}
				
				let totalSessions = 0;
				let totalResponseTime = 0;
				let totalDuration = 0;
				let totalScore = 0;
				let scoreCount = 0;
				
				stats.forEach(stat => {
					totalSessions += stat.totalSessions || 0;
					
					if (stat.avgResponseTime) {
						totalResponseTime += stat.avgResponseTime;
					}
					
					if (stat.avgSessionDuration) {
						totalDuration += stat.avgSessionDuration;
					}
					
					if (stat.satisfactionAvgScore) {
						totalScore += stat.satisfactionAvgScore;
						scoreCount++;
					}
				});
				
				this.summaryStats = {
					totalSessions,
					avgResponseTime: stats.length > 0 ? totalResponseTime / stats.length : 0,
					avgSessionDuration: stats.length > 0 ? totalDuration / stats.length : 0,
					satisfactionAvgScore: scoreCount > 0 ? totalScore / scoreCount : 0
				};
			},
			formatSeconds(seconds) {
				if (!seconds) return '0分0秒';
				
				const minutes = Math.floor(seconds / 60);
				const remainingSeconds = Math.floor(seconds % 60);
				
				if (minutes >= 60) {
					const hours = Math.floor(minutes / 60);
					const remainingMinutes = minutes % 60;
					return `${hours}小时${remainingMinutes}分`;
				}
				
				return `${minutes}分${remainingSeconds}秒`;
			},
			viewDetails(stat) {
				this.detailData = { ...stat };
				this.showDetailsModal = true;
			},
			async recalculateStats(serviceId) {
				try {
					const res = await api.customerService.recalculateStats({
						date: this.date
					});
					if (res.code === 200) {
						uni.showToast({
							title: '重新计算成功',
							icon: 'success'
						});
						this.showDetailsModal = false;
						this.loadStats();
					} else {
						uni.showToast({
							title: res.message || '重新计算统计失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '重新计算统计失败',
						icon: 'none'
					});
				}
			},
			formatDateTime(timeArray) {
				return formatTimeArray(timeArray);
			},
			formatRelativeTime(timeArray) {
				return getRelativeTime(timeArray);
			}
		}
	}
</script>

<style>
	.customer-service-stats {
		padding: 8px;
	}
	
	/* 过滤栏样式 */
	.filter-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
	}
	
	.date-filter {
		display: flex;
		align-items: center;
	}
	
	.filter-label {
		margin-right: 8px;
		font-size: 14px;
		color: #666;
	}
	
	.date-picker {
		border: 1px solid #d9d9d9;
		border-radius: 4px;
		padding: 6px 10px;
		min-width: 120px;
	}
	
	.picker-value {
		font-size: 14px;
		color: #333;
	}
	
	.refresh-btn {
		display: flex;
		align-items: center;
		color: #1890ff;
		font-size: 14px;
		cursor: pointer;
	}
	
	.refresh-icon {
		margin-right: 4px;
	}
	
	/* 统计总览样式 */
	.stats-overview {
		display: flex;
		flex-wrap: wrap;
		gap: 16px;
		margin-bottom: 16px;
	}
	
	.stat-card {
		flex: 1;
		min-width: 150px;
		background-color: white;
		border-radius: 4px;
		padding: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
		text-align: center;
	}
	
	.stat-title {
		font-size: 14px;
		color: #666;
		margin-bottom: 8px;
	}
	
	.stat-value {
		font-size: 24px;
		font-weight: bold;
		color: #333;
	}
	
	/* 分区卡片样式 */
	.section-card {
		background-color: white;
		border-radius: 4px;
		padding: 16px;
		margin-bottom: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	}
	
	.section-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 16px;
		border-bottom: 1px solid #f0f0f0;
		padding-bottom: 8px;
	}
	
	/* 排行榜样式 */
	.ranking-header {
		display: flex;
		background-color: #fafafa;
		padding: 8px 0;
		border-bottom: 1px solid #f0f0f0;
		font-weight: 500;
	}
	
	.ranking-th {
		flex: 1;
		padding: 0 8px;
		text-align: center;
		font-size: 14px;
		color: #666;
	}
	
	.ranking-item {
		display: flex;
		padding: 12px 0;
		border-bottom: 1px solid #f5f5f5;
		align-items: center;
	}
	
	.ranking-item:last-child {
		border-bottom: none;
	}
	
	.ranking-item.top-rank {
		background-color: #fafafa;
	}
	
	.ranking-td {
		flex: 1;
		padding: 0 8px;
		text-align: center;
		font-size: 14px;
		color: #333;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.rank {
		flex: 0.5;
	}
	
	.rank-badge {
		width: 24px;
		height: 24px;
		border-radius: 50%;
		color: white;
		display: flex;
		justify-content: center;
		align-items: center;
		font-weight: bold;
		font-size: 12px;
	}
	
	.rank-1 {
		background-color: #f5222d;
	}
	
	.rank-2 {
		background-color: #fa8c16;
	}
	
	.rank-3 {
		background-color: #faad14;
	}
	
	.satisfaction-stars {
		display: flex;
		margin-right: 4px;
	}
	
	.star {
		color: #d9d9d9;
		margin-right: 2px;
	}
	
	.star.active {
		color: #faad14;
	}
	
	.satisfaction-score {
		margin-left: 4px;
	}
	
	.empty-data {
		text-align: center;
		color: #999;
		padding: 24px 0;
	}
	
	/* 表格样式 */
	.stats-table {
		width: 100%;
	}
	
	.table-header {
		display: flex;
		background-color: #fafafa;
		border-bottom: 1px solid #f0f0f0;
	}
	
	.th {
		padding: 12px 8px;
		text-align: center;
		font-weight: 500;
		color: #666;
		flex: 1;
		font-size: 14px;
	}
	
	.tr {
		display: flex;
		border-bottom: 1px solid #f5f5f5;
	}
	
	.tr:last-child {
		border-bottom: none;
	}
	
	.td {
		padding: 12px 8px;
		flex: 1;
		text-align: center;
		font-size: 14px;
	}
	
	.btn {
		padding: 4px 8px;
		border: none;
		border-radius: 4px;
		cursor: pointer;
		font-size: 12px;
	}
	
	.btn-primary {
		background-color: #1890ff;
		color: white;
	}
	
	.btn-small {
		padding: 4px 8px;
		font-size: 12px;
	}
	
	/* 模态框样式 */
	.modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1000;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.modal-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.45);
	}
	
	.modal-content {
		position: relative;
		width: 90%;
		max-width: 500px;
		background-color: white;
		border-radius: 4px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
		display: flex;
		flex-direction: column;
		max-height: 80vh;
	}
	
	.modal-header {
		padding: 16px;
		border-bottom: 1px solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.modal-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}
	
	.modal-close {
		font-size: 20px;
		color: #999;
		cursor: pointer;
	}
	
	.modal-body {
		padding: 16px;
		overflow-y: auto;
		flex: 1;
	}
	
	/* 详情样式 */
	.detail-section {
		margin-bottom: 20px;
	}
	
	.detail-title {
		font-size: 16px;
		font-weight: 500;
		color: #333;
		margin-bottom: 12px;
		border-bottom: 1px solid #f0f0f0;
		padding-bottom: 8px;
	}
	
	.detail-item {
		display: flex;
		margin-bottom: 10px;
	}
	
	.detail-label {
		width: 120px;
		color: #666;
		font-size: 14px;
	}
	
	.detail-value {
		flex: 1;
		color: #333;
		font-size: 14px;
	}
</style> 